package com.jxb.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 对称二叉树
 *
 * @author jiaobo
 * @date Created in 2024/12/11 21:49
 **/
public class SymmetricTree_101 {

    public static void main(String[] args) {

    }

    //递归
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return deepCheck(root.left,root.right);
    }

    boolean deepCheck(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }
        if (left == null || right == null) {
            return false;
        }
        if (left.val != right.val) {
            return false;
        }
        return deepCheck(left.left,right.right) && deepCheck(left.right,right.left);
    }

    //用队列实现
    public boolean isSymmetricWithQueue(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        TreeNode left = root.left;
        TreeNode right = root.right;
        if (root == null || (left == null && right == null)) {
            return true;
        }
        q.offer(left);
        q.offer(right);
        while (!q.isEmpty()) {
            left = q.poll();
            right = q.poll();
            if (left == null && right == null) {
                continue;
            }
            if (left == null || right == null || (left.val != right.val)) {
                return false;
            }
            q.offer(left.left);
            q.offer(right.right);

            q.offer(left.right);
            q.offer(right.left);
        }
        return true;
    }

}
